#!/usr/bin/env python

"""test script for motionbin"""

import gtk, pygtk
import gst, pygst
import sys, time
import StringIO

from motionbin import MotionBin


class Main(object):

    def on_message(self, bus, message):
        t = message.type
        if (t == gst.MESSAGE_APPLICATION and
            message.structure.get_name() == 'motion_detection_results'):
            val = message.structure['value']
            clk = message.structure['time']
            self.label.set_text('%4f' % val)
            print 'detection level:',val
        elif (t == gst.MESSAGE_ELEMENT and 
            message.structure.get_name() == 'pixbuf'):
            pixbuf = message.structure['pixbuf']
            #self.gtkimg.set_from_pixbuf(pixbuf)
            if self.m.detector.motion_image:
                img = self.pil_image_to_gdk_pixbuf(self.m.detector.motion_image)
                self.gtkimg.set_from_pixbuf(img)
            
    def on_close(self, e):
        self.p.set_state(gst.STATE_NULL)
        gtk.main_quit()

    def __init__(self):
        
        wnd = gtk.Window()
        wnd.set_title('motionbin test')
        wnd.set_border_width(6)
        wnd.set_resizable(False)
        
        self.gtkimg = gtk.Image()
        self.label = gtk.Label('')
        
        vbox = gtk.VBox(homogeneous=False, spacing=6)
        
        vbox.pack_start(self.gtkimg, True, True)
        vbox.pack_start(self.label, False, False)
        
        wnd.add(vbox)
        wnd.connect('destroy', self.on_close)
        wnd.show_all()
        
        self.p = gst.Pipeline('test_pipeline')
        
        v = gst.element_factory_make('v4l2src', 'videosrc')
        
        self.m = MotionBin()
       
        self.p.add(v, self.m)
        gst.element_link_many(v, self.m)
        
        bus = self.p.get_bus()
        bus.add_signal_watch()
        bus.connect('message', self.on_message)
        bus.connect('message', self.m.on_message)
        
        self.p.set_state(gst.STATE_PLAYING)
    
    def pil_image_to_gdk_pixbuf(self, image):  
        """Convert a PIL Image to a gtk.gdk.Pixbuf"""  
        file1 = StringIO.StringIO()  
        image.save(file1, "ppm")  
        contents = file1.getvalue()  
        file1.close()  
        loader = gtk.gdk.PixbufLoader("pnm")  
        loader.write(contents, len(contents))  
        pixbuf = loader.get_pixbuf()  
        loader.close()  
        return pixbuf
        

if __name__ == '__main__':
    m = Main()
    gtk.main()
